//
//  DataManager.m
//  lisure0.1
//
//  Created by xalo on 16/4/22.
//  Copyright © 2016年 Mr.wangYongxu. All rights reserved.
//

#import "DataManager.h"
#import "ReadListModel.h"
#import <UIKit/UIKit.h>
#import "DownLoadModel+CoreDataProperties.h"
#import "PlayInfoModel.h"

/**
 *  NSManagerContext 用来关联上下文，相当于秘书职位
 *  NSManagedObjectMode 关联数据库模型
 *  NSPersistentStoreCoordinator 数据持久化处理，将数据写入本地
 */

@implementation DataManager

+(instancetype)defauleDataManager{

    static DataManager *hanadle = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        hanadle = [[DataManager alloc] init];
    });
    return hanadle;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        //关联上下文
        _context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
        NSManagedObjectModel* model = [[NSManagedObjectModel alloc] initWithContentsOfURL:[[NSBundle mainBundle] URLForResource:@"SaveModel" withExtension:@"momd"]];//url文件路径
        //负责数据持久化的类
        NSPersistentStoreCoordinator* store = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
        NSString* doucumentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
        NSString* fileName = [doucumentPath stringByAppendingPathComponent:@"model.sqlite"];
        [store addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:fileName] options:nil error:nil];
        NSLog(@"%@",fileName);
        self.context.persistentStoreCoordinator = store;
    }
    return self;
}

//
-(void)InsertData:(ReadListModel*)model{

    if ([self isContainData:model]) {
        NSLog(@"已经收藏");
        [self creadtAlertViewWithTitle:@"提示" message:@"已收藏"];
        return;
    }

    CollectionModel *collectionModel = [NSEntityDescription insertNewObjectForEntityForName:@"CollectionModel" inManagedObjectContext:self.context];
    //给实体的属性赋值
    collectionModel.title = model.title;
    collectionModel.coverimg = model.coverimg;
    collectionModel.content = model.content;
    collectionModel.typeID = model.contentid;
    [self.context save:nil];
    [self creadtAlertViewWithTitle:@"提示" message:@"收藏成功"];
}

//查
-(NSArray*)selectedData{


    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"CollectionModel" inManagedObjectContext:self.context];
    [fetchRequest setEntity:entity];
    NSError *error = nil;
    NSArray *fetchedObjects = [self.context executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"空");
    }
    return fetchedObjects;
}
//查
-(BOOL)isContainData:(ReadListModel*)model{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"CollectionModel"];

    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"typeID = %@",model.contentid];
    [request setPredicate:predicate];
    NSArray* array = [self.context executeFetchRequest:request error:nil];

    return array.count;
}

////删除
//-(void)deleteDate:(ReadListModel*)model{
//    [self.context deleteObject:model];
//}

-(void)creadtAlertViewWithTitle:(NSString*)title message:(NSString*)message{

//    UIAlertController* alertVontroller = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];

    UIAlertView* alert = [[UIAlertView alloc]initWithTitle:title message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}

#pragma mark - 下载

//
-(void)InsertDataWithModel:(PlayInfoModel*)model withFilePath:(NSString*)filePath{

//    if ([self isContainData:model]) {
//        NSLog(@"已经收藏");
//        [self creadtAlertViewWithTitle:@"提示" message:@"已收藏"];
//        return;
//    }

    DownLoadModel *downloadModel = [NSEntityDescription insertNewObjectForEntityForName:@"DownLoadModel" inManagedObjectContext:self.context];
    //给实体的属性赋值
    downloadModel.title = model.title;
    downloadModel.musicurl = model.musicUrl;
    downloadModel.image = model.imgUrl;
    downloadModel.filePath = filePath;
    [self.context save:nil];
    [self creadtAlertViewWithTitle:@"提示" message:@"下载成功"];
}

//查下载
-(NSArray*)DataWithDownLoad{

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownLoadModel" inManagedObjectContext:self.context];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"<#format string#>", <#arguments#>];
//    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
//    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"<#key#>"
//                                                                   ascending:YES];
//    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];

    NSError *error = nil;
    NSArray *fetchedObjects = [self.context executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"%ld",error.code);
    }
    return fetchedObjects;
}


@end
